package com.example.j202411.views.Activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import com.example.j202411.R;
import com.example.j202411.views.Fragment.ChatFragment;
import com.example.j202411.views.Fragment.FragmentHome;
import com.example.j202411.views.Fragment.FragmentTools;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout mTabOne;
    private LinearLayout mTabTwo;
    private LinearLayout mTabThree;
    private Fragment mContentFragment;
    private FragmentHome mfragmentHome;
    private ChatFragment mfragmentChatgpt;
    private FragmentTools mfragmentTools;
    private FragmentManager mfragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTabOne = findViewById(R.id.tabA);
        mTabTwo = findViewById(R.id.tabB);
        mTabThree = findViewById(R.id.tabC);
        mTabOne.setOnClickListener(this);
        mTabTwo.setOnClickListener(this);
        mTabThree.setOnClickListener(this);
        initFragment();
        changeFragment(mfragmentHome);
        mfragmentManager.beginTransaction()
                .add(R.id.fragment_content, mfragmentHome).commitAllowingStateLoss();
        mContentFragment = mfragmentHome;
        mTabOne.setSelected(true);
    }

    private void initFragment() {
        mfragmentManager = getSupportFragmentManager();
        mfragmentHome = new FragmentHome();
        mfragmentChatgpt =new ChatFragment();
        mfragmentTools = new FragmentTools();

    }


    public void changeFragment(Fragment to) {
        if (mContentFragment != null && mContentFragment != to) {
            if (!to.isAdded()) {
                mfragmentManager.beginTransaction().hide(mContentFragment)
                        .add(R.id.fragment_content, to).commitAllowingStateLoss();
            } else {
                mfragmentManager.beginTransaction().hide(mContentFragment)
                        .show(to).commitAllowingStateLoss();
            }
            mContentFragment = to;
        }
    }

    @Override
    public void onClick(View v) {
int id =v.getId();
if (id==R.id.tabA){
    mTabOne.setSelected(true);
    mTabTwo.setSelected(false);
    mTabThree.setSelected(false);
    changeFragment(mfragmentHome);
} else if (id==R.id.tabB) {
    mTabOne.setSelected(false);
    mTabTwo.setSelected(true);
    mTabThree.setSelected(false);
    changeFragment(mfragmentChatgpt);
} else if (id==R.id.tabC) {
    mTabOne.setSelected(false);
    mTabTwo.setSelected(false);
    mTabThree.setSelected(true);
    changeFragment(mfragmentTools);
}
    }
}